<template>
    <div style="display: flex;justify-content: center;align-items: center;">
        <div>
            姓名: <input type="text" v-model="neName" style="height: 30px;width: 200px"><br>
            密码: <input type="password" v-model="nePassword" style="height: 30px;width: 200px"/><br>

        </div>
        <button @click="login" style="align-items: center;width: 100px;height: 20px">登录</button>
    </div>
</template>

<script>
import {reactive, ref, toRefs} from 'vue';
import {urls} from "@/api/api";
import {post} from "@/api/request";
import {jwtDecode} from "jwt-decode";
import router from "@/router";

export default {
    setup() {
        const User = reactive({
            neName: "",
            nePassword: ""
        });
        const login = async () => {
            try {
                const response = await post(urls.m().login, {
                    neName: User.neName,
                    nePassword: User.nePassword
                });
                if (response.code === 200) {
                    localStorage.setItem('token', response.data);
                    const Token = localStorage.getItem('token')
                    if (localStorage.getItem('token') === response.data) {
                        console.log('Token has been successfully saved!');
                    } else {
                        console.log('Failed to save the token.')
                    }
                    const decoded = jwtDecode(Token);
                    console.log(decoded)
                    const role = decoded.claims.role;
                    console.log(role)

                    // 对身份进行判断，不同身份进入不同导航页
                    if(role === '普通员工'){
                        await router.push('/generalHome')
                    }else{
                        await router.push('/managerHome')
                    }
                    alert("登陆成功")
                } else {
                    console.log(response)
                    alert(response.message)
                    console.log('登陆失败：' + response.message)
                }
            } catch (error) {
                console.error(error);
            }
        };
        return {
            ...toRefs(User), login
        }
    }
}
</script>
